﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media.Animation;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Windows.Controls;
using System.Windows;

namespace BlueRadar.UI
{
    class StatusIndicatorAnimation
    {
        private DoubleAnimation da1;
        private GradientStop s1;
        private GradientStop s2;
        private Rectangle rect;
        private LinearGradientBrush animatedBrush;
        private SolidColorBrush inanimateBrush;

        public StatusIndicatorAnimation(Rectangle rect)
        {
            this.rect = rect;
            da1 = new DoubleAnimation(1, 0, TimeSpan.FromSeconds(2));
            da1.RepeatBehavior = RepeatBehavior.Forever;
            da1.AutoReverse = true;
            s1 = new GradientStop(Colors.Transparent, 0);
            s2 = new GradientStop(Colors.Blue, 1);
            animatedBrush = new LinearGradientBrush();
            animatedBrush.GradientStops.Add(s1);
            animatedBrush.GradientStops.Add(s2);

            inanimateBrush = Brushes.Transparent;
        }

        public void ShowImage(Image image)
        {
            double animationLength;
            EllipseGeometry ellipseGeometry = new EllipseGeometry();
            ellipseGeometry.RadiusX = 0;
            ellipseGeometry.RadiusY = 0;
            double centrex = image.Source.Width / 2;
            double centrey = image.Source.Height / 2;
            ellipseGeometry.Center = new Point(centrex, centrey);

            image.Clip = ellipseGeometry; //The most important line

            if (image.Source.Width > image.Source.Height)
                animationLength = image.Source.Width / 2;
            else
                animationLength = image.Source.Height / 2;
            DoubleAnimation a = new DoubleAnimation();
            a.From = 0;
            a.To = animationLength + 50;
            a.Duration = new Duration(TimeSpan.Parse("0:0:10"));
            ellipseGeometry.BeginAnimation(EllipseGeometry.RadiusXProperty, a);
            ellipseGeometry.BeginAnimation(EllipseGeometry.RadiusYProperty, a);
        }

        public void Start()
        {
            rect.Visibility = System.Windows.Visibility.Visible;
            s1.BeginAnimation(GradientStop.OffsetProperty, da1);
            rect.Fill = animatedBrush;
        }

        public void Stop()
        {
            rect.Visibility = System.Windows.Visibility.Hidden;
            rect.Fill = inanimateBrush;
        }
    }
}
